package com.yuyou.train.user.service.impl;

import java.util.*;

import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.yuyou.train.service.api.admin.entity.CommDataConfig;
import com.yuyou.train.service.api.admin.service.CommDataConfigAPI;
import com.yuyou.train.service.api.lesson.dto.UserLessonTreeDTO;
import com.yuyou.train.service.api.lesson.entity.Lesson;
import com.yuyou.train.service.api.lesson.entity.LessonClass;
import com.yuyou.train.service.api.lesson.entity.LessonClassUserRelation;
import com.yuyou.train.service.api.lesson.service.LessonAPI;
import com.yuyou.train.service.api.user.dto.UserPageDTO;
import com.yuyou.train.service.api.user.entity.User;
import com.yuyou.train.service.api.user.entity.UserDataConfig;
import com.yuyou.train.service.api.user.entity.UserImport;
import com.yuyou.train.service.api.user.entity.UserLessonProgress;
import com.yuyou.train.user.mapper.UserMapper;
import com.yuyou.train.user.service.IUserDataConfigService;
import com.yuyou.train.user.service.IUserImportService;
import com.yuyou.train.user.service.IUserLessonProgressService;
import com.yuyou.train.user.service.IUserMedalItemService;
import com.yuyou.train.user.service.IUserMedalRelationService;
import com.yuyou.train.user.service.IUserPointsService;
import com.yuyou.train.user.service.IUserService;
import com.yuyou.train.user.service.IUserTotalService;
import com.yuyou.train.user.vo.req.ReqBehavior;
import com.yuyou.train.user.vo.req.ReqUser;
import com.yuyou.train.user.vo.req.UserExcel;
import com.yuyou.train.user.vo.resp.RespClassStatis;
import com.yuyou.train.user.vo.resp.RespHomepageOfTeacher;
import com.yuyou.train.user.vo.resp.RespMyStudent;
import com.yuyou.train.user.vo.resp.RespNextLessonContent;
import com.yuyou.train.user.vo.resp.RespRemindModule;
import com.yuyou.train.user.vo.resp.RespStudentOfClass;
import com.yuyou.train.user.vo.resp.RespTeacherInfo;
import com.yuyou.train.user.vo.resp.RespUserDetail;
import com.yuyou.train.user.vo.resp.RespUserInfo;
import com.yuyou.train.user.vo.resp.RespUserInfofiniLes;
import com.yuyou.train.util.bean.Pagination;
import com.yuyou.train.util.bean.ResBoolSimpleInfo;
import com.yuyou.train.util.constant.lesson.LessonCons;
import com.yuyou.train.util.constant.user.UserLessonProgressCons;
import com.yuyou.train.util.enums.CommEnums;
import com.yuyou.train.util.enums.admin.CommDataConfigEnums;
import com.yuyou.train.util.enums.lesson.LessonEnums;
import com.yuyou.train.util.enums.user.UserEnums;
import com.yuyou.train.util.enums.user.UserLessonProgressEnums;
import com.yuyou.train.util.enums.user.UserPointsEnums;
import com.yuyou.train.util.message.CommMess;
import com.yuyou.train.util.message.user.UserMess;
import com.yuyou.train.util.message.user.UserPointsMess;
import com.yuyou.train.util.tool.BeanUtils;
import com.yuyou.train.util.tool.DateUtil;
import com.yuyou.train.util.tool.DefindBeanUtils;
import com.yuyou.train.util.tool.MathUtils;
import com.yuyou.train.util.tool.Sequence;
import com.yuyou.train.util.tool.UUIDUtil;
import com.yuyou.train.util.tool.Validator;

@Service
public class UserServiceImpl implements IUserService{

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private IUserDataConfigService userDataConfigService;

	@Autowired
	private CommDataConfigAPI commDataConfigAPI;

	@Autowired
	private IUserImportService userImportService;

	@Autowired
	private LessonAPI lessonAPI;

	@Autowired
	private IUserMedalRelationService userMedalRelationService;

	@Autowired
	private IUserPointsService userPointsService;
	
	@Autowired
	private IUserLessonProgressService userLessonProgressService;

	@Autowired
	private IUserMedalItemService  userMedalItemService;
	
	@Autowired
	private IUserTotalService userTotalService;

	@Autowired
	private IUserLessonProgressService userLesProService;
	
	@Override
	public int deleteByPrimaryKey(String id) {
		User user=selectByPrimaryKey(id);
		if(user!=null){
			user.setIsDel(CommEnums.isDel.yes.getValue());
			this.updateByPrimaryKeySelective(user);
		}
		return 0;
	}

	@Override
	public int insert(User user) {
		user.setId(Sequence.getSequence().getNextId());
		user.setCreateTime(new Date());	
		user.setIsDel(CommEnums.isDel.no.getValue());
		return userMapper.insert(user);
	}

	@Override
	public User selectByPrimaryKey(String id) {
		return userMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(User user) {
		user.setUpdateTime(new Date());
		return userMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public List<UserPageDTO> findUserPageList(Pagination<UserPageDTO> p) {
		return userMapper.findUserPageList(p);
	}

	@Override
	public int findUserPageCount(Pagination<UserPageDTO> p) {
		return userMapper.findUserPageCount(p);
	}

	@Override
	public List<User> findUsers(ReqUser reqUser) {
		return userMapper.findUsers(reqUser);
	}

	@Override
	public User selectUsersByPhone(String phone) {
		return userMapper.selectUsersByPhone(phone);
	}

	@Override
	public User selectUserByPhone(String phone) {
		return userMapper.selectUserByPhone(phone);
	}

	@Override
	@Transactional(timeout=60)
	public ResBoolSimpleInfo<User> updateUser(User user, List<String> subjectList, List<String> sectionList, List<String> tagList) throws Exception {

		ResBoolSimpleInfo<User> res = new ResBoolSimpleInfo<User>();

		if(CollectionUtils.isEmpty(subjectList)) {
			return new ResBoolSimpleInfo<>(false, UserMess.ERR_SUBJECT_EMPTY);
		}

		
		
		User userQuery = this.selectByPrimaryKey(user.getId());
		//科目
		if(UserEnums.isFirst.yes.getValue().equals(userQuery.getIsFirst())){
			
			// 首次登录分配导师
			if(UserEnums.type.student.getValue().equals(user.getType())){
				String teacherId=userMapper.selectChooseTeacher(subjectList.get(0),userQuery.getClassId());
				if(StringUtils.isEmpty(teacherId)){
					res.setSuccess(false);
					res.setMessage(UserMess.ERR_TEACHER_EMPTY);
					return res;
					
				}
				user.setParentId(teacherId);
			}
			
			if(userQuery.getType().equals(UserEnums.type.student.getValue())){
				//学员首次登录默认开启第一节
				ResBoolSimpleInfo<RespNextLessonContent> lesson=userLesProService.openUserNextLessonLock(user.getId(),subjectList.get(0),new ReqBehavior(),false);	
				if(!lesson.isSuccess()){
					res.setSuccess(false);
					res.setMessage(lesson.getMessage());
					return res;
				}			
			}	
			//首次登录注册送5分
			userPointsService.addPoints(user.getId(), UserPointsEnums.action.add.getValue(), String.format(UserPointsMess.ADD_REGIS_POINT, 5),5);
						
			userDataConfigService.deleteUserDataConfig(user.getId(), UserEnums.userDataConfigType.subject.getValue());
			for(String subjectId:subjectList){
				UserDataConfig uc = new UserDataConfig();
				uc.setUserId(user.getId());
				uc.setCommDataConfigId(subjectId);
				uc.setType(UserEnums.userDataConfigType.subject.getValue());
				userDataConfigService.insert(uc);
			}
			
		}

		user.setIsFirst(UserEnums.isFirst.no.getValue()); // 更新资料后不再是首次登录
		this.updateByPrimaryKeySelective(user);

			
		//学段
		if(!CollectionUtils.isEmpty(sectionList)){
			userDataConfigService.deleteUserDataConfig(user.getId(), UserEnums.userDataConfigType.section.getValue());
			for(String sectionId:sectionList){
				UserDataConfig uc=new UserDataConfig();
				uc.setUserId(user.getId());
				uc.setCommDataConfigId(sectionId);
				uc.setType(UserEnums.userDataConfigType.section.getValue());
				userDataConfigService.insert(uc);
			}
		}
		
		//标签
		if(!CollectionUtils.isEmpty(tagList)){
			userDataConfigService.deleteUserDataConfig(user.getId(), UserEnums.userDataConfigType.tag.getValue());
			for(String tag:tagList){
				UserDataConfig uc=new UserDataConfig();
				uc.setUserId(user.getId());
				uc.setCommDataConfigId(tag);
				uc.setType(UserEnums.userDataConfigType.tag.getValue());
				userDataConfigService.insert(uc);
			}
		}
		res.setData(user);
		res.setSuccess(true);
		
		return res;
	}

	@Override
	public ResBoolSimpleInfo<String> batchUpdSta(List<String> ids, String status) {
		userMapper.batchUpdSta(ids, status);
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	@Transactional(timeout=60)
	public UserImport saveUserImport(List<UserExcel> userExcelList, String type){
		int total = userExcelList.size();

		// 数据字典(科目)
		List<CommDataConfig> subjectDataConfigList = commDataConfigAPI.findUseByCategory(CommDataConfigEnums.category.subject.getValue());
		Map<String, CommDataConfig> subjectDataConfigMap = BeanUtils.toMap(subjectDataConfigList, "name");

		// 数据字典(学段)
		List<CommDataConfig> sectionDataConfigList = new ArrayList<>();
		if("0".equals(type)){
			sectionDataConfigList = commDataConfigAPI.findUseByCategory(CommDataConfigEnums.category.stage.getValue());
		}else if("1".equals(type)){
			sectionDataConfigList = commDataConfigAPI.findUseByCategory(CommDataConfigEnums.category.lessonType.getValue());
		}
		Map<String, CommDataConfig> sectionDataConfigMap = BeanUtils.toMap(sectionDataConfigList, "name");

		List<UserExcel> failUserList = checkUserImport(userExcelList, type, subjectDataConfigMap, sectionDataConfigMap);

		List<UserDataConfig> subjectOfUserDataConfigList = new ArrayList<>();
		List<UserDataConfig> sectionOfUserDataConfigList = new ArrayList<>();

		List<User> userList = new ArrayList<>();
		List<LessonClassUserRelation> lessonClassUserRelationList = new ArrayList<>();
		for(UserExcel userExcel : userExcelList){
			User user = new User();
			DefindBeanUtils.copyProperties(userExcel, user);
			user.setId(Sequence.getSequence().getNextId());
			user.setSource(UserEnums.source._import.getValue());
			user.setSex("男".equals(userExcel.getSex()) ? UserEnums.sex.male.getValue():(
					"女".equals(userExcel.getSex()) ? UserEnums.sex.female.getValue():UserEnums.sex.unknown.getValue()));
			user.setPassword("");
			user.setStatus(UserEnums.status.normal.getValue());
			user.setType(type);
			user.setLearnStatus(UserEnums.learnStatus.trainning.getValue());
			user.setIsDel(CommEnums.isDel.no.getValue());
			user.setIsFirst(UserEnums.isFirst.yes.getValue());
			user.setLoginErr(0);
			user.setCreateTime(DateUtil.now());
			userList.add(user);

			// 课程学生关系
			if(UserEnums.type.student.getValue().equals(type)){
				LessonClassUserRelation lessonClassUserRelation = new LessonClassUserRelation();
				lessonClassUserRelation.setId(Sequence.getSequence().getNextId());
				lessonClassUserRelation.setLessonClassId(userExcel.getClassId());
				lessonClassUserRelation.setLearnStatus(UserEnums.learnStatus.trainning.getValue());
				lessonClassUserRelation.setUserId(user.getId());
				lessonClassUserRelation.setType(type);
				lessonClassUserRelation.setCreateTime(DateUtil.now());

				lessonClassUserRelationList.add(lessonClassUserRelation);
			}

			// 用户信息字典(科目)数据
			if(!StringUtils.isEmpty(userExcel.getSubject())){
				String subject = userExcel.getSubject();
				String[] subjectList = subject.split(",");
				for(String subjectName: subjectList){
					if(null != subjectDataConfigMap.get(subjectName)){
						UserDataConfig subjectUserDataConfig = new UserDataConfig();

						subjectUserDataConfig.setId(Sequence.getSequence().getNextId());
						subjectUserDataConfig.setType(UserEnums.userDataConfigType.subject.getValue());
						subjectUserDataConfig.setUserId(user.getId());
						subjectUserDataConfig.setCreateTime(DateUtil.now());
						subjectUserDataConfig.setCommDataConfigId(subjectDataConfigMap.get(subjectName).getId());

						subjectOfUserDataConfigList.add(subjectUserDataConfig);
					}
				}
			}

			// 用户信息字典(学段)数据
			if(!StringUtils.isEmpty(userExcel.getSection())){
				String section = userExcel.getSection();
				String[] sectionList = section.split(",");
				for(String sectionName: sectionList){
					if(null != sectionDataConfigMap.get(sectionName)){
						UserDataConfig sectionUserDataConfig = new UserDataConfig();
						sectionUserDataConfig.setId(Sequence.getSequence().getNextId());
						sectionUserDataConfig.setType(UserEnums.userDataConfigType.section.getValue());
						sectionUserDataConfig.setUserId(user.getId());
						sectionUserDataConfig.setCreateTime(DateUtil.now());
						sectionUserDataConfig.setCommDataConfigId(sectionDataConfigMap.get(sectionName).getId());

						sectionOfUserDataConfigList.add(sectionUserDataConfig);
					}
				}
			}
		}

		if(userList.size() > 0){
			userMapper.batchInsertUser(userList);
		}
		if(subjectOfUserDataConfigList.size() > 0){
			userDataConfigService.batchInsertUserDataConfig(subjectOfUserDataConfigList);
		}
		if(sectionOfUserDataConfigList.size() > 0){
			userDataConfigService.batchInsertUserDataConfig(sectionOfUserDataConfigList);
		}

		if(lessonClassUserRelationList.size() > 0){
			userMapper.batchInsertLessonClassUserRelation(lessonClassUserRelationList);
		}

		/** 导入成败记录 */
		UserImport userImport = new UserImport();
		userImport.setId(Sequence.getSequence().getNextId());
		userImport.setTotal(total);
		userImport.setSuccNum(userExcelList.size());
		userImport.setFailNum(failUserList.size());
		userImport.setStatus(failUserList.size() > 0 ? "1" : "0");
		userImport.setType(type);
		userImport.setContent(JSON.toJSONString(failUserList));
		userImport.setCreateTime(DateUtil.now());
		userImportService.insert(userImport);

		return userImport;
	}


	@Override
	public XSSFWorkbook failedInfoOfUserImport(List<UserExcel> userExcelList){

		XSSFWorkbook excel = new XSSFWorkbook();

		XSSFSheet sheet = excel.createSheet("用户导入失败信息");

		XSSFRow firstRow = sheet.createRow(0);

		String[] titles = new String[] { "课程编号","姓名","手机号","性别","身份证","Email","毕业学校","专业信息","任教科目","任教学段","个人简介","导入失败原因"};

		for (int i = 0; i < titles.length; i++) {
			XSSFCell cell = firstRow.createCell(i);

			// 失败原因设置为红色
			if(i == titles.length -1){
				XSSFCellStyle cellStyle = excel.createCellStyle();
				cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
				cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
				cell.setCellStyle(cellStyle);
			}
			cell.setCellValue(titles[i]);
		}

		for (int i = 0; i < userExcelList.size(); i++ ) {

			UserExcel userExcel = userExcelList.get(i);

			XSSFRow row = sheet.createRow(i + 1);

			int c = 0;
			XSSFCell cell = row.createCell(c++);
			cell.setCellValue(userExcel.getCode());

			cell = row.createCell(c++);
			cell.setCellValue(userExcel.getUsername());

			cell = row.createCell(c++);
			cell.setCellValue(userExcel.getPhone());

			cell = row.createCell(c++);
			cell.setCellValue(userExcel.getSex());

			cell = row.createCell(c++);
			cell.setCellValue(userExcel.getIdCard());

			cell = row.createCell(c++);
			cell.setCellValue(userExcel.getEmail());

			cell = row.createCell(c++);
			cell.setCellValue(userExcel.getSchool());

			cell = row.createCell(c++);
			cell.setCellValue(userExcel.getMajor());

			cell = row.createCell(c++);
			cell.setCellValue(userExcel.getSubject());

			cell = row.createCell(c++);
			cell.setCellValue(userExcel.getSection());

			cell = row.createCell(c++);
			cell.setCellValue(userExcel.getIntroduction());

			cell = row.createCell(c++);
			// 失败原因设置为红色
			XSSFCellStyle cellStyle = excel.createCellStyle();
			cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
			cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
			cell.setCellStyle(cellStyle);
			cell.setCellValue(userExcel.getFailedReason());
		}
		return excel;
	}

	private List<UserExcel> checkUserImport(List<UserExcel> userExcelList, String type, Map<String, CommDataConfig> subjectDataConfigMap, Map<String, CommDataConfig> sectionDataConfigMap){
		// 导入失败的用户
		List<UserExcel> failUserList = new ArrayList<>();
		Iterator<UserExcel> iterator = userExcelList.iterator();
		Set<String> phoneSet = new HashSet<>();
		while(iterator.hasNext()){
			UserExcel userExcel = iterator.next();
			UserExcel failUser = new UserExcel();
			DefindBeanUtils.copyProperties(userExcel, failUser);
			StringBuilder failReason = new StringBuilder();

			if(type.equals(UserEnums.type.student.getValue())){
				if(StringUtils.isEmpty(userExcel.getCode())){
					failReason.append(";").append("课程编号 为空");
				}else{
					String code = userExcel.getCode();
					LessonClass lessonClass = lessonAPI.findLessonClassByCode(code);
					if(null == lessonClass){
						failReason.append(";").append("课程编号 有误");
					}else{
						userExcel.setClassId(lessonClass.getId());
					}
				}
			}

			if(StringUtils.isEmpty(userExcel.getUsername())){
				failReason.append(";").append("姓名为空");
			}else if(userExcel.getUsername().trim().length() > 50){
				failReason.append(";").append("姓名长度大于50");
			}

			if(StringUtils.isEmpty(userExcel.getPhone())){
				failReason.append(";").append("手机号为空");
			}else if(!Validator.isMobile(userExcel.getPhone().trim())){
				failReason.append(";").append("手机号不正确");
			}else if(phoneSet.contains(userExcel.getPhone().trim())){
				failReason.append(";").append("导入文件中该手机号已经存在");
			}else if(null != selectUserByPhone(userExcel.getPhone().trim())){
				// 手机号检测
				User user = selectUserByPhone(userExcel.getPhone().trim());
				if(CommEnums.isDel.no.getValue().equals(user.getIsDel())){
					failReason.append(";").append("该手机号已经存在");
				}else{
					failReason.append(";").append("该手机号已删除，不能再导入");
				}
			}else{
				phoneSet.add(userExcel.getPhone().trim());
			}

			if(!StringUtils.isEmpty(userExcel.getIdCard())){
				if(!Validator.isIDCard(userExcel.getIdCard().trim())){
					failReason.append(";").append("身份证不正确");
				}
			}

			if(!StringUtils.isEmpty(userExcel.getEmail())){
				if(!Validator.isEmail(userExcel.getEmail().trim())){
					failReason.append(";").append("Email 不正确");
				}
			}

			// 任教科目
			if(!StringUtils.isEmpty(userExcel.getSubject())){
				String subject = userExcel.getSubject();
				String[] subjectList = subject.split(",");
				for(String oneSubject : subjectList){
					if(!subjectDataConfigMap.containsKey(oneSubject)){
						failReason.append(";").append("任教科目有误");
					}
				}
			}

			// 任教学段
			if(!StringUtils.isEmpty(userExcel.getSection())){
				String section = userExcel.getSection();
				String[] sectionList = section.split(",");
				for(String oneSection: sectionList){
					if(!sectionDataConfigMap.containsKey(oneSection)){
						failReason.append(";").append("任教学段有误");
					}
				}
			}

			// 性别
			List<String> genders = Arrays.asList("男","女","未知");
			if(!StringUtils.isEmpty(userExcel.getSex()) && !genders.contains(userExcel.getSex())){
				failReason.append(";").append("性别有误");
			}

			if(!StringUtils.isEmpty(userExcel.getSchool()) && userExcel.getSchool().trim().length() > 100){
				failReason.append(";").append("毕业学校长度超100字");
			}

			if(!StringUtils.isEmpty(userExcel.getIntroduction()) && userExcel.getIntroduction().trim().length() > 500){
				failReason.append(";").append("个人简介长度超500字");
			}

			// 不符合的，移除不导入
			if(!StringUtils.isEmpty(failReason.toString())){
				failUser.setFailedReason(failReason.toString().substring(1, failReason.toString().length()));
				failUserList.add(failUser);
				iterator.remove();
			}
		}

		return failUserList;
	}

	public ResBoolSimpleInfo<String> delUser(String id) {
		ResBoolSimpleInfo<String> res=new ResBoolSimpleInfo<String>();
		User user=this.selectByPrimaryKey(id);
		//账号判断
		if(user.getStatus().equals(UserEnums.status.normal.getValue())){
			res.setSuccess(false);
			res.setMessage(UserMess.ERR_DEL_NORMAL_STATUS);
			return res;
		}
		
		if(user.getType().equals(UserEnums.type.teacher.getValue())){
			ReqUser condi=new ReqUser();
			condi.setParentId(user.getId());
			List<User> childList=this.findUsers(condi);
			if(childList.size()>0){
				res.setSuccess(false);
				res.setMessage(UserMess.ERR_DEL_HAS_STUDENT);
				return res;
			}
			
			List<LessonClassUserRelation> relList=lessonAPI.findTeacherClass(user.getId());
			if(relList.size()>0){
				res.setSuccess(false);
				res.setMessage(UserMess.ERR_DEL_HAS_CLASS);
				return res;
			}
		}
				
		//其他todo
		this.deleteByPrimaryKey(id);	
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	public RespUserDetail detailUser(String userId) {
		RespUserDetail res=new RespUserDetail();
		User user=this.selectByPrimaryKey(userId);
		DefindBeanUtils.copyProperties(user, res);
		//科目
		List<String> subjectList=userDataConfigService.findDataIdByUserIdAndType(userId, UserEnums.userDataConfigType.subject.getValue());
		res.setSubjectList(subjectList);
		//学段
		List<String> sectionList=userDataConfigService.findDataIdByUserIdAndType(userId, UserEnums.userDataConfigType.section.getValue());
		res.setSectionList(sectionList);
		//标签
		List<String> tagList=userDataConfigService.findDataIdByUserIdAndType(userId, UserEnums.userDataConfigType.tag.getValue());
		res.setTagList(tagList);	
		return res;
	}

	@Override
	public RespUserInfo userInfo(String userId) throws Exception {
		RespUserInfo res = new RespUserInfo();
		User user = this.selectByPrimaryKey(userId);
		DefindBeanUtils.copyProperties(user, res);

		// 设置班级名
		LessonClass lessonClass = lessonAPI.findLessonClassById(user.getClassId());
		res.setClassName(null != lessonClass ? lessonClass.getName() : "");

		//科目
		List<String> subjectList = userDataConfigService.findDataIdByUserIdAndType(userId, UserEnums.userDataConfigType.subject.getValue());
		res.setSubjectList(subjectList);
		//学段
		List<String> sectionList = userDataConfigService.findDataIdByUserIdAndType(userId, UserEnums.userDataConfigType.section.getValue());
		res.setSectionList(sectionList);
		//标签
		List<String> tagList = userDataConfigService.findDataIdByUserIdAndType(userId, UserEnums.userDataConfigType.tag.getValue());
		res.setTagList(tagList);

		// 勋章数
		res.setMedals(userMedalRelationService.countMedalByUserId(userId));

		// 获得的勋章
		res.setUserMedalList(userMedalItemService.findMedalByUserId(userId));

		//积分数量
		int points = userPointsService.sumPointsByUserId(userId, UserPointsEnums.action.add.getValue())
				- userPointsService.sumPointsByUserId(userId, UserPointsEnums.action.sub.getValue());

		res.setPoints(points);

		if(UserEnums.type.student.getValue().equals(user.getType())){
			//用户当前课程d
			UserLessonProgress currLesson=userLessonProgressService.getUserCurrLesson(user.getId(),user.getClassId());
			
			//如果是结果页
			if(null != currLesson&&currLesson.getLessonId().equals(UserLessonProgressCons.END_LESSON_ID1)){
				res.setProgress(100);
				res.setCurrentLesson(LessonCons.END_LEAF);
				res.setNextLesson(null);
				//进行中课程树
				UserLessonTreeDTO userLessonTreeDTO = userLessonProgressService.getUserchapterTree(currLesson.getLessonId(), userId);
				res.setOngoingLessonList(userLessonTreeDTO);
	
			}else if(null != currLesson){
				String subjectId=subjectList.get(0);
				//进行百分比
				ResBoolSimpleInfo<Integer> per=userLessonProgressService.getUserLessonPer(userId);
				if(per.isSuccess()){
					res.setProgress(per.getData());
				}
				//进行中课程名字
				Lesson lesson = lessonAPI.selectLessonById(currLesson.getLessonId());
				res.setCurrentLesson(lesson.getName());

				//下一节
				String nextLeId = userLessonProgressService.getUserNextLesson(user.getClassId(), userId, subjectId);
				Lesson nLesson = lessonAPI.selectLessonById(nextLeId);
				res.setNextLesson(nLesson.getName());

				//进行中课程树
				UserLessonTreeDTO userLessonTreeDTO = userLessonProgressService.getUserchapterTree(currLesson.getLessonId(), userId);
				res.setOngoingLessonList(userLessonTreeDTO);
			}
			//已完成课程
			RespUserInfofiniLes fini=null;
			LessonClass _class=lessonAPI.selectLastFinishClass(userId);	
			if(_class!=null){
				UserLessonProgress first=userLessonProgressService.getUserFirstLesson(_class.getId(),user.getId());
				res.setFinishedLesson(first!=null?new RespUserInfofiniLes(_class.getId(),first.getLessonId(),first.getResourceType(),_class.getName(),_class.getIntroduce()):null);
			}else{
				res.setFinishedLesson(fini);
			}
			return res;
		}

		return res;
	}

	@Override
	public RespTeacherInfo detailTeacher(String studentId, String teacherId){

		RespTeacherInfo respTeacherInfo = new RespTeacherInfo();

		User teacher = this.selectByPrimaryKey(teacherId);
		DefindBeanUtils.copyProperties(teacher, respTeacherInfo);

		// 科目
		List<String> subjectList = userDataConfigService.findDataNameByUserIdAndType(teacherId, UserEnums.userDataConfigType.subject.getValue());
		respTeacherInfo.setSubjectList(subjectList);
		// 学段
		List<String> sectionList=userDataConfigService.findDataNameByUserIdAndType(teacherId, UserEnums.userDataConfigType.section.getValue());
		respTeacherInfo.setSectionList(sectionList);
		//标签
		List<String> tagList=userDataConfigService.findDataNameByUserIdAndType(teacherId, UserEnums.userDataConfigType.tag.getValue());
		respTeacherInfo.setTagList(tagList);
		// 学生报名的班级信息
		List<LessonClass> lessonClassList = new ArrayList<>();
		User student = this.selectByPrimaryKey(studentId);
		LessonClass lessonClass = lessonAPI.findLessonClassById(student.getClassId());
		lessonClassList.add(lessonClass);
		respTeacherInfo.setLessonClassList(lessonClassList);

		return respTeacherInfo;
	}

	@Override
	@Transactional(timeout=60)
	public ResBoolSimpleInfo<String> endWord(String userId,String teacherId, String endWord) throws Exception {
		ResBoolSimpleInfo<String> res=new ResBoolSimpleInfo<String>();
		
		User user=this.selectByPrimaryKey(userId);
		if(user.getLearnStatus().equals(UserEnums.learnStatus.trainning.getValue())){
			res.setSuccess(false);
			res.setMessage(CommMess.ERR_POWER);
			return res;
		}
		
		if(!user.getParentId().equals(teacherId)){
			res.setSuccess(false);
			res.setMessage(CommMess.ERR_POWER);
			return res;
		}
		
		//假如已经毕业，只能更新结束语
		LessonClassUserRelation rel=lessonAPI.selectLesClsUseRel(user.getClassId(), userId, UserEnums.type.student.getValue());
		if(!StringUtils.isEmpty(rel.getEndWord())
				&& (user.getLearnStatus().equals(UserEnums.learnStatus.graduation.getValue()) 
						|| user.getLearnStatus().equals(UserEnums.learnStatus.fail.getValue()))){
			LessonClassUserRelation end=new LessonClassUserRelation();
			end.setId(rel.getId());
			end.setEndWord(endWord);
			end.setLearnStatus(user.getLearnStatus());
			userMapper.endLessonClass(end);
			return ResBoolSimpleInfo.getSuccessInfo();
		}
		

		
		
		String learnStatus=null;	
		double endMark=0;
		//算绩点，判断合格不
		List<UserLessonProgress> listP=userLessonProgressService.findByUserAttr(user.getId(),user.getClassId(),LessonEnums.attr.check.getValue());
		if(listP.size()==0){
			learnStatus=UserEnums.learnStatus.fail.getValue();
		}else{
			double totalMark=0;
			double totalMarkCon=0;
			for(UserLessonProgress up:listP){
				totalMark=totalMark+up.getGetMark();
				totalMarkCon=totalMarkCon+up.getMarkCon();
				
			}
			double count=0.0;
			if(totalMarkCon!=0){
				 count=MathUtils.div(totalMark, totalMarkCon,1);
			}			
			endMark=count;
			if(count>=UserLessonProgressCons.END_MARK_PASS){
				learnStatus=UserEnums.learnStatus.graduation.getValue();
			}else{
				learnStatus=UserEnums.learnStatus.fail.getValue();
			}
		}
			
		UserLessonProgress currP=userLessonProgressService.getUserCurrLesson(user.getId(),user.getClassId());
		UserLessonProgress updateP=new UserLessonProgress();
		updateP.setId(currP.getId());
		updateP.setGetMark(endMark);
		updateP.setStatus(UserLessonProgressEnums.status.studying.getValue());
		userLessonProgressService.updateByPrimaryKeySelective(updateP);
		
		User updateUser=new User();
		updateUser.setId(userId);
		updateUser.setLearnStatus(learnStatus);
		this.updateByPrimaryKeySelective(updateUser);		
//		LessonClassUserRelation rel=lessonAPI.selectLesClsUseRel(user.getClassId(), userId, UserEnums.type.student.getValue());
		
		LessonClassUserRelation end=new LessonClassUserRelation();
		end.setId(rel.getId());
		end.setLearnStatus(learnStatus);
		end.setEndWord(endWord);
		userMapper.endLessonClass(end);
				
		userTotalService.updateClassTotal(userId);
		
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	public ResBoolSimpleInfo<RespHomepageOfTeacher> homepageOfTeacher(String userId){
		ResBoolSimpleInfo resBoolSimpleInfo = new ResBoolSimpleInfo();
		RespHomepageOfTeacher homepageOfTeacher = new RespHomepageOfTeacher();

		RespMyStudent myStudent = new RespMyStudent();
		ReqUser myStudentQuery = new ReqUser();

		List<LessonClass> lessonClassList = lessonAPI.findLessonClassByUserId(userId);
		if(CollectionUtils.isEmpty(lessonClassList)){
			return new ResBoolSimpleInfo(false, UserMess.ERR_NO_CLASS);

		}
		List<String> lessonClassIds = BeanUtils.toList(lessonClassList, "id");

		// 我的学员
		myStudentQuery.setParentId(userId);
		myStudentQuery.setShowMyClass(userId);
		myStudent.setMyStudent(userMapper.countUsers(myStudentQuery));
		// 今日新增
		myStudentQuery.setRegTimeStart(DateUtil.getZeroOfToday());
		myStudent.setIncrementOfToday(userMapper.countUsers(myStudentQuery));
		// 培训中学员
		myStudentQuery.setRegTimeStart(null);
		myStudentQuery.setLearnStatus(UserEnums.learnStatus.trainning.getValue());
		myStudent.setTrainingStudent(userMapper.countUsers(myStudentQuery));
		// 班级学员统计
		List<RespClassStatis> classStatisList = new ArrayList<>();
		for(LessonClass lessonClass : lessonClassList){
			RespClassStatis classStatis = new RespClassStatis();
			classStatis.setLessonClassId(lessonClass.getId());
			classStatis.setLessonClassName(lessonClass.getName());
			myStudentQuery.setLearnStatus(null);
			myStudentQuery.setClassId(lessonClass.getId());
			classStatis.setSumOfStudent(userMapper.countUsers(myStudentQuery));
			classStatisList.add(classStatis);
		}
		myStudent.setClassStatis(classStatisList);


		RespStudentOfClass studentOfClass = new RespStudentOfClass();
		ReqUser studentOfClassQuery = new ReqUser();
		// 今日新增
		studentOfClassQuery.setClassIds(lessonClassIds);
		studentOfClassQuery.setShowMyClass(userId);
		studentOfClassQuery.setIsFirst(UserEnums.isFirst.no.getValue());
		studentOfClassQuery.setCreateTime(DateUtil.getZeroOfToday());
		studentOfClass.setIncrementOfToday(userMapper.countUsers(studentOfClassQuery));
		// 培训中学员
		studentOfClassQuery.setCreateTime(null);
		studentOfClassQuery.setLearnStatus(UserEnums.learnStatus.trainning.getValue());
		studentOfClass.setTrainingStudent(userMapper.countUsers(studentOfClassQuery));
		// 班级学员统计
		List<RespClassStatis> classStatisList2 = new ArrayList<>();
		Integer sumOfStudent = 0;
		for(LessonClass lessonClass : lessonClassList){
			RespClassStatis classStatis = new RespClassStatis();
			classStatis.setLessonClassId(lessonClass.getId());
			classStatis.setLessonClassName(lessonClass.getName());
			studentOfClassQuery.setClassIds(null);
			studentOfClassQuery.setLearnStatus(null);
			studentOfClassQuery.setClassId(classStatis.getLessonClassId());
			Integer sumOfClassStudent = userMapper.countUsers(studentOfClassQuery);
			classStatis.setSumOfStudent(sumOfClassStudent);
			sumOfStudent += sumOfClassStudent;
			classStatisList2.add(classStatis);
		}
		studentOfClass.setSumOfStudent(sumOfStudent);
		studentOfClass.setClassStatis(classStatisList2);


		RespRemindModule remindModule = new RespRemindModule();
		// 待评作业
		remindModule.setHomework(userMapper.countHomework(userId));
		// 考核（我的学生）
		remindModule.setCheckOfMyStudent(userMapper.countCheckOfMyStudent(userId));
		// 考核（班级学生）
		remindModule.setCheckOfClassStudent(userMapper.countCheckOfClassStudent(userId));
		// 结课寄语
		remindModule.setEndWord(userMapper.countEndWord(userId));

		homepageOfTeacher.setMyStudent(myStudent);
		homepageOfTeacher.setStudentOfClass(studentOfClass);
		homepageOfTeacher.setRemindModule(remindModule);

		resBoolSimpleInfo.setSuccess(true);
		resBoolSimpleInfo.setMessage(null);
		resBoolSimpleInfo.setData(homepageOfTeacher);
		return resBoolSimpleInfo;
	}

	@Override
	public int findTeacherPageCount(Pagination<UserPageDTO> p) {
		return userMapper.findTeacherPageCount(p);
	}

	@Override
	public List<UserPageDTO> findTeacherPageList(Pagination<UserPageDTO> p) {
		return userMapper.findTeacherPageList(p);
	}
}
